package com.ctgu.redislock03.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.redislock03.entity.OrdersEntity;
import com.ctgu.redislock03.entity.VoucherEntity;
import com.ctgu.redislock03.mapper.OrdersMapper;
import com.ctgu.redislock03.service.OrdersService;
import com.ctgu.redislock03.service.VoucherService;
import com.ctgu.redislock03.utils.ApiResult;
import com.ctgu.redislock03.utils.RedisIdWorker;
import com.ctgu.redislock03.utils.redisLock.RedisLock;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
* @author Alex2
* @description 针对表【t_orders】的数据库操作Service实现
* @createDate 2025-03-07 17:44:43
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersEntity>
    implements OrdersService {

    @Autowired
    private VoucherService voucherService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisIdWorker redisIdWorker;

    @Override
    public ApiResult fetchVoucher(Integer voucherId, Integer userId) {
        VoucherEntity voucher = voucherService.lambdaQuery().eq(VoucherEntity::getId, voucherId).one();
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return ApiResult.error("秒杀未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return ApiResult.error("秒杀已结束");
        }
        if (voucher.getStock() < 1) {
            return ApiResult.error("库存不足");
        }
        RedisLock lock = new RedisLock("order" + userId, redisTemplate);
        boolean isLock = lock.lock(60);     //60秒后锁自动释放
        //加锁失败
        if (!isLock) {
            return ApiResult.error("不能重复下单");
        }
        try {
            // 获取事务有关代理对象
            OrdersService proxy = (OrdersService) AopContext.currentProxy();
            return proxy.createOrder(voucherId, userId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    @Override
    @Transactional
    public ApiResult createOrder(Integer voucherId, Integer userId) {

        Long count = lambdaQuery().eq(OrdersEntity::getUserId, userId).eq(OrdersEntity::getVoucherId, voucherId).count();
        if (count > 0) {
            return ApiResult.error("用户已经购买过一次");
        }
        //扣减库存
        boolean update = voucherService.lambdaUpdate()
                .setSql("stock = stock - 1")
                .eq(VoucherEntity::getId, voucherId)
                .gt(VoucherEntity::getStock, 0)
                .update();

        if (!update) {
            return ApiResult.error("库存不足");
        }
        long orderId = redisIdWorker.getNextId("order");
        OrdersEntity ordersEntity = new OrdersEntity(orderId, userId, voucherId);
        save(ordersEntity);
        return ApiResult.success("秒杀成功", ordersEntity);
    }
}